<?php
session_start();
ob_start();

$cfg_file = fopen(dirname(__FILE__).'/../sonare-config.txt', 'r');

$fb = trim(fgets($cfg_file)) === 'on'; // firebug mode on/off

$cfg = array(
	'oskey' => trim(fgets($cfg_file)),
	'ossecret' => trim(fgets($cfg_file)),
	'lfmkey' => trim(fgets($cfg_file)),
	'lfmsecret' => trim(fgets($cfg_file))
);

fclose($cfg_file);

header("Content-Type: text/html; charset=utf-8");
header("Cache-Control: private,max-age=1");

if ($fb) {
	require_once dirname(__FILE__).'/../Library-FirePHPCore-0.3/lib/FirePHPCore/FirePHP.class.php';
	$firephp = FirePHP::getInstance(true);
}
/*
require_once dirname(__FILE__).'/../opensocial-php-client/src/osapi/osapi.php';

$oid = $_REQUEST['oid']; // OpenSocialID (owner)
$vid = $_REQUEST['vid']; // OpenSocialID (viewer)
$view = $_REQUEST['view']; // profile | canvas

$storage = new osapiFileStorage(dirname(__FILE__).'/../tmp/osapi');
$provider = new osapiOrkutProvider();

$auth = new osapiOAuth2Legged($cfg['oskey'], $cfg['ossecret'], $oid);
$osapi = new osapi($provider, $auth);

$request = $osapi->people->get(array('userId'=>'@me', 'groupId'=>'@self'));
$batch = $osapi->newBatch();
$batch->add($request, 'request_label');
$result = $batch->execute();

$fb && $firephp->info($result, 'result');
$fb && $firephp->trace('tracing, yeah');
*/
$username = '';
if (empty($_REQUEST['username'])) {
	exit ('__MSG_APP_MISS_USERNAME__');
    exit ('<strong>Erro: informe seu login Last.fm na página de configurações.<br />Error: please set your Last.fm username first.</strong>');
} else {
	$username = $_REQUEST['username'];
}

$path_lastfm_api = dirname(__FILE__).'/../lastfmapi';
require $path_lastfm_api.'/lastfmapi.php';

$authVars = array(
	'apiKey' => $cfg['lfmkey'],
);
$config = array(
	'enabled' => true,
	'path' => $path_lastfm_api.'/',
	'cache_length' => 1800 // TODO como se configura isto? nao sera este o problema dos icones que nao vem?
);

$auth = new lastfmApiAuth('setsession', $authVars);
$apiClass = new lastfmApi();
$userClass = $apiClass->getPackage($auth, 'user', $config);

$methodVars = array(
	'user' => $username
);

$tracks = $userClass->getRecentTracks($methodVars);

foreach ($tracks as $i => $t) {
	$tracks[$i]['images']['hassmall'] = ! empty($t['images']['small']);
	$tracks[$i]['images']['hasmedium'] = ! empty($t['images']['medium']);
	$tracks[$i]['images']['haslarge'] = ! empty($t['images']['large']);
}

// if (profile view) {...} else it's canvas view
if (!empty($_REQUEST['json'])) {
    // TODO http://mdj.us/web-development/php-programming/another-variation-on-the-time-ago-php-function-use-mysqls-datetime-field-type/
    foreach ($tracks as $i => $t) {
        $tracks[$i]['date'] = date('d/m/Y H:i:s', $t['date']);
        $tracks[$i]['images']['hassmall'] = ! empty($t['images']['small']);
        $tracks[$i]['images']['hasmedium'] = ! empty($t['images']['medium']);
    }
    echo json_encode($tracks);
    exit;
}

?>
<h2><a title="__MSG_VIEW_PROFILE__" href="__MSG_LASTFM_URL__/user/<?php echo $username ?>/" target="_blank">__MSG_HEADING__ <?php echo $username ?></a></h2>
<div class="datalist">
	<?php if (empty($tracks)): ?>
	<span><strong>__MSG_ERROR__ <?php echo $userClass->error['code'] ?> - </strong><em><?php echo $userClass->error['desc'] ?></em></span>
	<?php else: ?>
	<table>
		<tbody>
			<?php foreach ($tracks as $track): ?>
			<?php $track['nowplaying'] = ! empty($track['nowplaying']) ?>
			<tr <?php echo $track['nowplaying'] ? 'class="now-playing"' : '' ?>>
				<td class="icon-cell"><?php
					$html = '<a href="%s" target="_blank"><img alt="" width="%s" src="%s" /></a>';
					if ($track['nowplaying']) {
						if ($track['images']['hasmedium']) printf($html, $track['url'], 64, $track['images']['medium']);
					} else {
						if ($track['images']['hassmall']) printf($html, $track['url'], 34, $track['images']['small']);
					}
				?></td>
				<td class="play-cell">
					<?php if($track['streamable']): ?>
					<a title="__MSG_PLAY__" rel="nofollow" href="<?php echo $track['url'] ?>?autostart" class="icon playbutton" target="_blank"></a>
					<?php endif ?>
				</td>
				<td class="subject-cell">
					<a href="__MSG_LASTFM_URL__/music/<?php echo urlencode($track['artist']['name']) ?>" target="_blank">
					<?php echo $track['artist']['name'] ?>
					</a> - 
					<a href="<?php echo $track['url'] ?>" target="_blank"><?php echo $track['name'] ?></a>
				</td>
				<td class="love-cell">
					<?php if(false): // TODO how to check if it's a loved track? ?>
					<a title="A loved track" class="icon lovedicon"></a>
					<?php endif ?>
				</td>
				<td class="date-cell">
					<?php if($track['nowplaying']): ?>
					<img src="http://andregs.net.br/dev/lastfm-for-orkut/image/icon_eq.gif" width="12" height="12"><span> __MSG_LISTENING_NOW__</span>
					<?php else: ?>
					<span class="date"><?php 
						// TODO http://mdj.us/web-development/php-programming/another-variation-on-the-time-ago-php-function-use-mysqls-datetime-field-type/
						echo date('d/m/Y H:i:s', $track['date']) 
					?></span>
					<?php endif ?>
				</td>
			</tr>
			<?php endforeach ?>
		</tbody>
	</table>
	<?php endif ?>
    <div id="footer"><a href="javascript:void(0)" title="__MSG_SETTINGS__" class="icon settings_icon" onclick="control.showFrmConfig()"><span>__MSG_SETTINGS__</span></a></div>
</div>